package com.tj.ocr.similar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageIndex {
	private List<FingerPrint> fingerList;
	private Map<Integer,Map<Integer,List<Integer>>> data;
		
	public ImageIndex(){
		fingerList = new ArrayList<>();
		data = new HashMap<>();
	}
	
	public FingerPrint get(FingerPrint print, int height){
		//get by rowid
		int rowId = print.getRowId();
		
		if(data.containsKey(rowId)){
			Map<Integer,List<Integer>> m = data.get(rowId);
			//get by colId
			int colId = print.getColId();
			if(m.containsKey(colId)){
				List<Integer> lds = m.get(colId);
				if(lds.size() == 1)
					return fingerList.get(lds.get(0));
				for(int ld : lds){
					//get id
					FingerPrint fp = fingerList.get(ld);
					if(fp.isSimilar(print))
						return fp;
				}
			}
		}
		
		return null;
	}
	
	public void add(FingerPrint print, int height){
		
		//add to list
		this.fingerList.add(print);
		int index = this.fingerList.size() - 1;
		
		//set row info
		int rowId = print.getRowId();
		for(int i=-3;i<4;i++){
			Map<Integer,List<Integer>> cols = data.get(rowId+i);
			if(cols == null){
				cols = new HashMap<>();
				data.put(rowId+i, cols);
			}
			
			//set col info
			int col = print.getColId();
			for(int j=-3;j<4;j++){
				int colId = col + j;
				List<Integer> fs = cols.get(colId);
				if(fs == null){
					fs = new ArrayList<>();
					cols.put(colId, fs);
				}
				
				//add item
				fs.add(index);
			}
		}
	}
	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		
		for(Integer ri : this.data.keySet()){
			System.out.println(" ,"+ri);
			Map<Integer,List<Integer>> mil = this.data.get(ri);
			for(Integer mi : mil.keySet()){
				System.out.print(" , ,"+mi+", ,");
				List<Integer> ll = mil.get(mi);
				for(int ii : ll){
					System.out.print(ii + ",");
				}
				System.out.println();
			}	
		}
		
		return sb.toString();
	}
}
